﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace JQueryWidget.WidgetFrame.Common
{
    public class TemplateColumn:System.Web.UI.UserControl,ITemplateColumn
    {

        #region ITemplateColumn Members

        public int TemplateDataID
        {
            get;
            set;
        }

        public bool NeedWrapper
        {
            get;
            set;
        }

        public string ColumnID
        {
            get;
            set;
        }

        public virtual void LoadWidgets()
        {
            if (TemplateDataID > 0)
            {
                var templateData = (from td in XDocument.Load(Server.MapPath("~/Data/templatedata.xml")).Element("templatedatas").Elements("templatedata")
                                    where td.Element("id").Value == TemplateDataID.ToString()
                                    select td).FirstOrDefault();
                if (templateData != null)
                {
                    var column = (from c in templateData.Element("columns").Elements("column")
                                   where c.Attribute("id").Value == ColumnID.ToString()
                                   select c).FirstOrDefault();
                    if ( column != null)
                    {
                        var columnId = column.Attribute("id").Value;
                        var widgets = (from w in column.Element("widgets").Elements("widget")
                                       select w).ToList();
                        foreach (var widget in widgets)
                        {
                            var widgetWrapper = CreateNewWidgetWrapper();
                            widgetWrapper.LoadWidget(widget);
                            var columnContainer = GetColumnContainer(); System.Web.UI.IAttributeAccessor attributeAccessor = columnContainer as System.Web.UI.IAttributeAccessor;
                            attributeAccessor.SetAttribute("columnid", ColumnID);
                            columnContainer.Controls.Add(widgetWrapper as System.Web.UI.Control);
                        }
                    }
                }
            }
        }

        public virtual IWidgetWrapper CreateNewWidgetWrapper()
        {
            var widgetWrapperSrc = NeedWrapper ? "~/Modules/WidgetWrapper.ascx" : "~/Modules/BlankWidgetWrapper.ascx";
            return Page.LoadControl(widgetWrapperSrc) as IWidgetWrapper;
        }


        public virtual System.Web.UI.Control GetColumnContainer()
        {
            return this;
        }
        #endregion
         
    }
}